package com.yjhb.android.sbz.tool;

import android.app.Activity;
import android.content.Context;

import com.alipay.sdk.app.PayTask;
import com.yjhb.android.sbz.Conf;
import com.jojo.android.zxlib.interfaces.Callback;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建者 zx
 * 创建时间 2020/12/3 11:11
 */
public class PayTool {
    private final String TAG = "PayTool";


    /**
     * 支付宝
     *
     * @param activity
     * @param result
     */
    public static void AliPay(final Activity activity, final String orderInfo, final Callback<Map<String, String>> result) {
        Observable.create(new ObservableOnSubscribe<Map<String, String>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String, String>> e) throws Exception {
                PayTask payTask = new PayTask(activity);
//                EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX); //开起沙箱环境
                e.onNext(payTask.payV2(orderInfo, true));
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Map<String, String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Map<String, String> stringStringMap) {
                        result.callback(stringStringMap);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }




    //微信支付
    public static void payWechat(Context context, String sign, String prepayId, String nonceStr, String timestamp) {
        final IWXAPI wxapi = WXAPIFactory.createWXAPI(context, null);
        PayReq payReq = new PayReq();
        payReq.appId = Conf.WX_APP_ID;
        payReq.partnerId = Conf.WX_APP_PARTNER_Id;
        payReq.prepayId = prepayId;
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = nonceStr;
        payReq.timeStamp = timestamp;
        Map<String, Object> map = new HashMap<>();
        map.put("appid", payReq.appId);
        map.put("partnerid", payReq.partnerId);
        map.put("prepayid", payReq.prepayId);
        map.put("package", payReq.packageValue);
        map.put("noncestr", payReq.nonceStr);
        map.put("timestamp", payReq.timeStamp);
        payReq.sign = sign;
        wxapi.sendReq(payReq);
    }


    private static String sign(Map<String, Object> map) {
        map = removeMapNullField(map);
        Map<String, Object> sort = createDictSortMap(map);
        String string = mapToString(sort) + "key=XXXXXXXXXXXXXXXXXXXXXX"; //防止信息泄露，已转由服务器签验
        return MD5(string).toUpperCase();
    }

    private static Map<String, Object> createDictSortMap(Map<String, Object> map) {
        ArrayList<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys);
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        for (String key : keys) {
            sortMap.put(key, map.get(key));
        }
        return sortMap;
    }

    private static Map<String, Object> removeMapNullField(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() == null) {
                map.remove(entry.getKey());
            }
        }
        return map;
    }

    private static String mapToString(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        for (String key : map.keySet()) {
            sb.append("" + key + "=" + map.get(key) + "&");
        }
        return sb.toString();
    }

    private static String MD5(String str) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ignored) {
        }
        byte[] array = md.digest(str.getBytes(StandardCharsets.UTF_8));
        StringBuilder sign = new StringBuilder();
        for (byte item : array) {
            sign.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sign.toString();
    }

}
